package com.qf.web.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import com.qf.common.base.exception.ServiceException;
import com.qf.common.base.result.ResultCode;
import com.qf.web.config.OSSConfigProperties;
import com.qf.web.service.UploadService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.io.File;
import java.io.IOException;
import java.util.Date;

@Service
public class UploadServiceImpl implements UploadService {
    public static final String IMG_PREFIX_FILE = "IMG_";
    public static final String DATE_FORMAT = "yyyyMMddHHmmss";
    public static final String BUCKET_NAME_IMAGE = "images";
    @Resource
    private OSS oss;
    @Resource
    private OSSConfigProperties properties;

    /**
     * 图片覆盖
     * /1/20210314/xxx.png
     * 36655/按着日期对文件归类 // 可以防止图片覆盖
     * // 对图片重命名
     *
     * @return
     */
    @Override
    public String uploadImage(MultipartFile multipartFile) {
        /**
         * 获取文件的原始名称
         */
        // 判断文件的格式
        String originalFilename = multipartFile.getOriginalFilename();
        // 判断文件是否是上传格式
        String newFileName = getNewFileName(originalFilename);
        String key = BUCKET_NAME_IMAGE + File.separator + DateUtil.format(new Date(), "yyyy-MM-dd") + File.separator + newFileName;
        try {
            PutObjectResult putObjectResult = oss.putObject(properties.getBucketName(), key, multipartFile.getInputStream());
            if (!ObjectUtil.isEmpty(putObjectResult.getETag())) {
                // 表示上传成功
                return getUrl(properties.getBucketName(), key);
            } else {
                throw new ServiceException(ResultCode.FILE_UPLOAD_ERROR);
            }
        } catch (IOException e) {
            throw new ServiceException(ResultCode.FILE_UPLOAD_ERROR);
        }
    }

    /**
     * 对图片进行重命名
     *
     * @param originalFilename
     * @return
     */
    private static String getNewFileName(String originalFilename) {
        /**
         * 自定义命名规则 + 文件的后缀名
         * IMG_2022031415331234.png
         * xxxx.png
         */

        // 获取文件的后缀名
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        return String.format("%s%s%s%s", IMG_PREFIX_FILE, DateUtil.format(new DateTime(), DATE_FORMAT), RandomUtil.randomNumbers(4), suffixName);
    }


    private String getUrl(String bucketName, String key) {
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        String url = oss.generatePresignedUrl(bucketName, key, expiration).toString();
        return url;
    }

}
